import pandas as pd
from feature_conf.config import GenericConfigConstant
import re
from datetime import datetime, timedelta



def time_trans(time, country_id):
    """
    时间转换
    :param time:  时间
    :param country_id: 国家id，如'mx'
    :return:  格式化后的时间
    """
    tz = GenericConfigConstant.COUNTRY_TIME_ZONE[country_id.lower()]
    time_len = len(str(time))
    time_format = "%a %b %d %H:%M:%S GMT%z %Y"
    if time_len == 10:
        format_time = datetime.utcfromtimestamp(int(time)) + timedelta(hours=tz)
    elif time_len == 13:
        format_time = datetime.utcfromtimestamp(int(time) // 1000) + timedelta(hours=tz)
    elif time_len == 34:
        format_time = datetime.strptime(str(time), time_format)
    else:
        format_time = datetime(2099, 12, 31, 23, 59, 59)
    return format_time


def process_app_data(app_data, apply_time,country_id):
    """
    处理传入的app数据，list of json
    Args:
        app_data:app数据
        apply_time:申请时间
        country_id:国家id
    """

    assert country_id in GenericConfigConstant.COUNTRY_ID, "country id not in list, Please input correct country id"
    if app_data is None or app_data.shape[0] == 0:
        return pd.DataFrame(columns=['app_name', 'fi_time', 'lu_time', 'fi_day', 'fi_hour', 'fi_weekday', 'fi_month',
                                     'lu_day', 'lu_hour', 'lu_weekday', 'lu_month'])

    # app_data = json.loads(app_data)
    # app_df = pd.DataFrame(app_data)
    # 将时间戳转成country_id对应的时间
    app_data['fi_time'] = pd.to_datetime(app_data['fi_time'], unit='ms') + pd.Timedelta(hours=GenericConfigConstant.COUNTRY_TIME_ZONE[country_id])
    app_data['lu_time'] = pd.to_datetime(app_data['lu_time'], unit='ms') + pd.Timedelta(hours=GenericConfigConstant.COUNTRY_TIME_ZONE[country_id])
    app_data = app_data[app_data['fi_time'] < apply_time]

    # 每个人选取最近的3000条短信
    app_data = app_data.sort_values(by='fi_time', ascending=False).head(3000)

    # 时间相关处理
    app_data['fi_day'] = app_data['fi_time'].dt.date
    app_data['fi_hour'] = app_data['fi_time'].dt.hour
    app_data['fi_weekday'] = app_data['fi_time'].dt.weekday
    app_data['fi_month'] = app_data['fi_time'].dt.month

    app_data['lu_day'] = app_data['lu_time'].dt.date
    app_data['lu_hour'] = app_data['lu_time'].dt.hour
    app_data['lu_weekday'] = app_data['lu_time'].dt.weekday
    app_data['lu_month'] = app_data['lu_time'].dt.month

    app_data['app_name'] = app_data['app_name'].apply(lambda x: x.lower())
    return app_data